<?php

/**
 * 用户名：明文存放。
 * 登录序列：一个被MD5散列过的随机数，仅当强制用户输入口令时更新（如：用户修改了口令）。
 * 登录token：一个被MD5散列过的随机数，仅一个登录session内有效，新的登录session会更新它。
 */
class SecurityCenter
{
    protected $CI;
    public static $security_center_config = array(
        'cookie_login' => true,

    );
    protected $cookie_list = array();
    protected $user_info;
    protected $cookie_vaild_time = 60 * 60 * 24 * 3;//有效时间为三日

    public function __construct()
    {
        $this->CI = &get_instance();
    }

    public function cookieLogin()
    {
        if (!SecurityCenter::$security_center_config['cookie_login']) {
            return false;
        }
        $this->getCookieList();
        if (empty($this->cookie_list['al_username'])) {//cookie无数据,跳过cookie登录
            return false;
        }
        $this->CI->load->model('lyw_cookie_login_model');
        $db_info = $this->CI->lyw_cookie_login_model->getOneListInfoByUsername($this->cookie_list['al_username']);
        if (empty($db_info)) {
            return false;
        }
        if ($db_info['vaild_time'] < time()) {//过期了
            return false;
        }
        /*---判断token是否相同---*/
        if ($this->cookie_list['al_token'] == $db_info['token']) {//token正确,可以用作登录
            //判断order是否相同
            if ($this->cookie_list['al_order'] == $db_info['c_order']) {//序列相同,该cookie未被盗用
                echo 1;
                /*-------开始自动登录-------*/
                $this->autoLoginById($db_info['user_id']);
                //登录成功了,修改token
                $new_token = $this->changeToken($db_info['user_id']);
                $this->setCookieList(array('al_token', $new_token));
                //注意:在输入密码账号登录的时候必须更新order
                return true;
            } else {//序列不同,该cookie可能被盗用,要求客户重新输入账号密码登录
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 获取cookie列表
     */
    protected function getCookieList()
    {
        $this->cookie_list = array(
            'al_username' => isset($_COOKIE["al_username"]) ? $_COOKIE["al_username"] : '',
            'al_order' => isset($_COOKIE["al_order"]) ? $_COOKIE["al_order"] : '',
            'al_token' => isset($_COOKIE["al_token"]) ? $_COOKIE["al_token"] : '',
        );
    }

    protected function autoLoginById($user_id)
    {
        $this->CI->load->model('lyw_user_model');
        $user_info = $this->CI->lyw_user_model->getUserInfor($user_id);
        sessionOpen();
        $_SESSION['user_id'] = $user_info['id'];
        $_SESSION['user_type'] = $user_info['type'];
        $_SESSION['username'] = $user_info['username'];
        $_SESSION['header_image'] = $user_info['header_image'];
    }

    /**
     * 正常登录后调用这个方法
     */
    public function commonLogin()
    {
        sessionOpen();
        $this->CI->load->model('lyw_cookie_login_model');
        if ($this->CI->lyw_cookie_login_model->had($_SESSION['user_id'])) {
            $this->changeOrder($_SESSION['user_id']);
            $this->changeToken($_SESSION['user_id']);
        } else {
            $new_order = $this->buildOrder();
            $new_token = $this->buildToken();
            $this->CI->lyw_cookie_login_model->add($_SESSION['user_id'], $_SESSION['username'], $new_token, $new_order, $this->cookie_vaild_time);
        }
        $result = $this->CI->lyw_cookie_login_model->getOneListInfoByUserId($_SESSION['user_id']);
        $arr = array(
            'al_username' => $_SESSION['username'],
            'al_order' => $result['c_order'],
            'al_token' => $result['token'],
        );
        $this->setCookieList($arr);
    }

    /**
     * 设置登录cookie数据
     */
    public function setCookieList($arr)
    {
        foreach ($arr as $key => $value) {
            setcookie($key, $value, time() + $this->cookie_vaild_time, '/', '.whereiam.cn');
        }
    }

    public function buildToken()
    {//8位随机字符加密
        return md5(sha1(getRandStr(8)));
    }

    public function buildOrder()
    {//8位随机字符加密
        return md5(sha1(getRandStr(8)));
    }

    public function changeToken($user_id)
    {
        $new_token = $this->buildToken();
        $this->CI->load->model('lyw_cookie_login_model');
        $this->CI->lyw_cookie_login_model->changeToken($user_id, $new_token, $this->cookie_vaild_time);
        return $new_token;
//        $this->setCookieList(array('al_token', $new_token));//数据库和本地cookie都要修改
    }

    public function changeOrder($user_id)
    {
        $new_order = $this->buildOrder();
        $this->CI->load->model('lyw_cookie_login_model');
        $this->CI->lyw_cookie_login_model->changeOrder($user_id, $new_order, $this->cookie_vaild_time);
        return $new_order;
//        $this->setCookieList(array('al_order', $new_order));//数据库和本地cookie都要修改
    }
}